package cn.edu.seig.himusic.minio;

import io.minio.MinioClient;
import io.minio.UploadObjectArgs;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MinioDirectoryUploader {

  public static void main(String[] args) throws Exception {
    // MinIO客户端初始化
    MinioClient minioClient =
        MinioClient.builder()
            .endpoint("http://127.0.0.1:9000")
            .credentials("minioadmin", "minioadmin")
            .build();

    String bucketName = "vibe-music-data";
    String localDir = "E:/code_all_E/backEnd/OpenSource/music-platform/other-resource"; // 本地目录
    String remoteBasePath = "";  // 上传到桶里的前缀，可以为空字符串

    uploadDirectory(minioClient, bucketName, localDir, remoteBasePath);
  }

  public static void uploadDirectory(MinioClient minioClient,
                                     String bucketName,
                                     String localDir,
                                     String remoteBasePath) throws Exception {

    Path basePath = Paths.get(localDir);

    // 递归遍历目录
    Files.walk(basePath)
        .filter(Files::isRegularFile) // 只处理文件
        .forEach(path -> {
          try {
            // 相对路径
            String relativePath = basePath.relativize(path).toString().replace('\\', '/');

            // MinIO 对象名（目录层次保留）
            String objectName = remoteBasePath + relativePath;

            System.out.println("Uploading: " + path + " -> " + objectName);

            // 覆盖式上传
            minioClient.uploadObject(
                UploadObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .filename(path.toString())
                    .build()
            );
          } catch (Exception e) {
            e.printStackTrace(System.err);
            throw new RuntimeException(e);
          }
        });
  }
}
